//
//  MessageTextBubbleView.m
//  BaiTengIM
//
//  Created by awh on 2019/6/29.
//  Copyright © 2019 awh. All rights reserved.
//

#import "MessageTextBubbleView.h"
#import "TextMessageModel.h"
#import "StickerDataManager.h"
#import "StickerModel.h"
@implementation MessageTextBubbleView

- (instancetype)initWithDirection:(MessageDirection)messageDirection type:(MessageType)messageType {
    self = [super initWithDirection:messageDirection type:messageType];
    if (self) {
        [self setupSubviews];
    }
    
    return self;
}

#pragma mark - Subviews

- (void)setupSubviews
{
    [self setupBubbleBackgroundImage];
    
    self.textLabel = [[YYLabel alloc] init];
    self.textLabel.userInteractionEnabled = YES;
    self.textLabel.font = [UIFont systemFontOfSize:15];
    self.textLabel.numberOfLines = 0;
    self.textLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - 70 - 60 - 20;
    [self addSubview:self.textLabel];
    [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(10);
        make.bottom.equalTo(self.mas_bottom).offset(-10);
    }];
    
    if (self.messageDirection == MessageDirectionSend) {
        self.textLabel.textColor = [UIColor whiteColor];
        [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mas_left).offset(15);
            make.right.equalTo(self.mas_right).offset(-15);
        }];
    } else {
        self.textLabel.textColor = [UIColor blackColor];
        [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mas_left).offset(15);
            make.right.equalTo(self.mas_right).offset(-15);
        }];
    }
    
    // 图片解析器
    YYTextSimpleEmoticonParser *parser = [YYTextSimpleEmoticonParser new];
    NSMutableDictionary *mapper = [NSMutableDictionary new];
    NSArray<StickerModel *> *stickers = [StickerDataManager sharedInstance].allStickers;
    [stickers enumerateObjectsUsingBlock:^(StickerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImage *image = [UIImage imageNamed:obj.image];
        if (image) {
            NSString *key = [NSString stringWithFormat:@"[%@]", obj.desc];
            [mapper setObject:image forKey:key];
        }
    }];
//    mapper[@"[爱哭]"] = [UIImage imageNamed:@"emotion_aiku"];
//    mapper[@":cool:"] = [UIImage imageNamed:@"cool.png"];
//    mapper[@":cry:"] = [UIImage imageNamed:@"cry.png"];
//    mapper[@":wink:"] = [UIImage imageNamed:@"wink.png"];
    parser.emoticonMapper = mapper;
    self.textLabel.textParser = parser;
}



- (void)setModel:(BTMessageModel *)model {
    TextMessageModel *textModel =  (TextMessageModel *)model;
    NSString *content = textModel.msg;
    if ([textModel.msg containsString:kAtDividedSymbols]) {
        NSArray<NSString *> *coms = [textModel.msg componentsSeparatedByString:kAtDividedSymbols];
        content = coms[0];
    }
    content = [NSObject ldy_isEmpty:content] ? @" " : content;
//    self.textLabel.text = content;
//    self.textLabel.textColor = model.messageDirection == MessageDirectionSend ? [UIColor blackColor] : [UIColor whiteColor];
    
    
    // 转成可变属性字符串
    NSMutableAttributedString * mAttributedString = [NSMutableAttributedString new];
    
    // 调整行间距段落间距
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    [paragraphStyle setLineSpacing:2];
    [paragraphStyle setParagraphSpacing:4];
    
    // 设置文本属性
    UIColor *color =  model.messageDirection == MessageDirectionSend ? KHEXCOLOR(kBlackColor) : KHEXCOLOR(kBlackColor);
    NSDictionary *attri = [NSDictionary dictionaryWithObjects:@[[UIFont systemFontOfSize:15], color, paragraphStyle] forKeys:@[NSFontAttributeName, NSForegroundColorAttributeName, NSParagraphStyleAttributeName]];
    [mAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:content attributes:attri]];

    // 匹配条件
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSError *error = NULL;
    // 根据匹配条件，创建了一个正则表达式
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];
    if (!regex) {
        AAIMLog(@"正则创建失败error！= %@", [error localizedDescription]);
    } else {
        NSArray *allMatches = [regex matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
        for (NSTextCheckingResult *match in allMatches) {
            NSString *substrinsgForMatch2 = [mAttributedString.string substringWithRange:match.range];
            substrinsgForMatch2 = [NSObject ldy_isEmpty:substrinsgForMatch2] ? @"" : substrinsgForMatch2;
            NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:substrinsgForMatch2];
            // 利用YYText设置一些文本属性
            one.font = [UIFont systemFontOfSize:15];
            one.underlineStyle = NSUnderlineStyleSingle;
            one.color = model.messageDirection == MessageDirectionReceive ? [UIColor colorWithRed:0.093 green:0.492 blue:1.000 alpha:1.000] : [UIColor redColor];
            YYTextBorder *border = [YYTextBorder new];
            border.cornerRadius = 3;
            border.insets = UIEdgeInsetsMake(-2, -1, -2, -1);
            border.fillColor = [UIColor colorWithWhite:0.000 alpha:0.220];
            
            YYTextHighlight *highlight = [YYTextHighlight new];
            [highlight setBorder:border];
            [one setTextHighlight:highlight range:one.rangeOfAll];
            // 根据range替换字符串
            [mAttributedString replaceCharactersInRange:match.range withAttributedString:one];
            WS(ws);
            [_textLabel setHighlightTapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
                NSString *string = [NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]];
                AAIMLog(@"%@", string);
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[text.string substringWithRange:range]]]];
                if (ws.delegate && [ws.delegate respondsToSelector:@selector(messageBubbleView:didClickURL:)]) {
                    [ws.delegate messageBubbleView:ws didClickURL:[NSString stringWithFormat:@"%@",[text.string substringWithRange:range]]];
                }
            }];
        }
    }
    mAttributedString.lineSpacing = 5.0;
    self.textLabel.attributedText = mAttributedString;
    
//    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
//    attachment.image = [UIImage imageNamed:@"男"];
//    attachment.bounds = CGRectMake(0, 0, 30, 30);
//    NSMutableAttributedString *emojiAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
//    self.textLabel.attributedText = emojiAttributedString;
}

@end
